from app.account.models import UserInfo, EmailVerifyRecord
from rest_framework.views import APIView
from common.authCheck.userAuth import check_login, getUser
from django.http import JsonResponse


class ActiveUserView(APIView):

    @check_login
    def get(self, request, active_code):
        """
        激活用户账户
        :param request:
        :param active_code:
        :return:
        """
        try:
            record = EmailVerifyRecord.objects.filter(code__exact=active_code)
            if not record.exists():
                return JsonResponse({
                    'status': False,
                    'errMsg': '验证码不存在'
                }, status=404)
            record = record[0]
            if record.code_status == 'used':
                return JsonResponse({
                    'status': False,
                    'errMsg': '该验证码已经过期了'
                }, status=401)
            user = getUser(request.session.get('login'))
            if record.email == user.email:
                user.user_role = '4'
                user.save()
                record.code_status = 'used'
                record.save()
                return JsonResponse({
                    'status': True,
                    'id': user.id
                })
            else:
                return JsonResponse({
                    'status': False,
                    'errMsg': '激活失败'
                }, status=401)
        except Exception as ex:
            return JsonResponse({
                'status': False,
                'errMsg': str(ex)
            }, status=403)
